package wangjg.security.deprecated;

import java.util.Iterator;
import java.util.Set;

import wangjg.security.core.AuthoritySet;


public class RoleValidator implements ResourceValidator{
	private boolean allowAll ;
	private Set roles ;
	
	public RoleValidator() {
	}

	public boolean validate(Object resource, Object user){
		if(allowAll){
			return true;
		}
		if(user instanceof RoleHolder){
			Set userRoles=((RoleHolder)user).getRoles();
			boolean b=this.checkRoles(userRoles,resource);
			if(b)return true;
		}
		if(user instanceof AuthoritySet){
			Set ats=((AuthoritySet)user).getAuthorities();
			if(this.checkAuthority(ats,resource)){
				return true;
			}
		}
		return false;
	}
	
	private boolean checkRoles(Set userRoles,Object resource){
		if(userRoles==null||userRoles.size()==0||roles==null||roles.size()==0){
			return false;
		}
		Iterator it=userRoles.iterator();
		while(it.hasNext()){
			Object role=it.next();
			if(this.roles.contains(role)){
				return true;
			}
			if(role instanceof AuthoritySet){
				Set ats=((AuthoritySet)role).getAuthorities();
				if(this.checkAuthority(ats,resource)){
					return true;
				}
			}
		}
		return false;
		
	}
	
	/*
	 * 
	 * @param usersAuthorities 用户拥有的权限
	 * @return
	 */
	private boolean checkAuthority(Set userAuthorities,Object resource){
		if(!(resource instanceof AuthoritySet)){
			return false;
		}
		Set ras = ((AuthoritySet)resource).getAuthorities();
		if(ras==null || userAuthorities==null){
			return false;
		}
		for(Object ua:ras){
			if(userAuthorities.contains(ua)){
				return true;
			}
		}
		return false;
	}
	
	public boolean isAllowAll() {
		return allowAll;
	}

	public void setAllowAll(boolean allowAll) {
		this.allowAll = allowAll;
	}

	public Set getRoles() {
		return roles;
	}

	public void setRoles(Set allowedRoles) {
		this.roles = allowedRoles;
	}

	public String toString() {
		return "RoleValidator [allowAll=" + allowAll + ", allowedRoles="
				+ roles + "]";
	}

}
